// 库引入
import React, {Component} from 'react';
import {inject, observer} from 'mobx-react';
import classNames from 'classnames';
import {observable, action, computed, reaction} from 'mobx';
import fp from 'lodash/fp';

// 样式引入
import styles from './style.module.less';

// 一些值
const f = f=>f;

@observer
class Search extends Component {

  disposers = [];

  /**
   * 搜索条件
   */
  @observable filter = '';

  /**
   * 搜索条件是否为空
   */
  @computed get isFilterEmpty() {
    return this.filter === '';
  }

  /**
   * 设置搜索条件
   * @param {string} filter 搜索条件
   */
  @action setFilter = (filter) => {
    this.filter = filter;
  }

  /**
   * 输入框onChange事件
   */
  @action handleInputChange = (e) => {
    const {value, name} = e.target;
    this[name] = value;
  }

  /**
   * 按钮点击事件
   */
  handleBtnClick = () => {
    if (!this.isFilterEmpty) {
      // 当搜索条件不为空的时候需要清除搜索条件
      this.setFilter('');
    }
  }

  /**
   * debounce变化节流事件
   */
  debounceOnChange = fp.debounce(this.props.debounce, (filter) => {
    this.props.onChange(filter);
  });

  componentDidMount() {
    this.setFilter(this.props.defaultValue);
    this
      .disposers
      .push(reaction(() => this.filter, (filter) => {
        // 响应filter变化
        if(this.props.debounce) {
          // 如果需要节流
          this.debounceOnChange(filter);
        }else {
          this.props.onChange(filter);
        }
      }));
  }

  componentWillUnmount() {
    this
      .disposers
      .forEach(disposer => disposer());
  }

  render() {
    return (
      <div
        className={classNames(styles.search, this.props.className)}
        style={this.props.style}>
        <input
          className={styles.input}
          type="text"
          name="filter"
          onChange={this.handleInputChange}
          onKeyDown={this.handleKeyDown}
          value={this.filter}
          placeholder="搜索开源库，例如jquery"/>
        <i
          className={classNames('iconfont', {
          'icon-sousuo': this.isFilterEmpty,
          'icon-cuowuguanbiquxiao': !this.isFilterEmpty
        }, styles.btn)}
          onClick={this.handleBtnClick}></i>
      </div>
    );
  }
}

Search.defaultProps = {
  onChange: f,
  debounce: 500,
  defaultValue: ''
};

const InjectSearch = inject(({
  libsStore = {}
}) => ({onChange: libsStore.setFilters,defaultValue: libsStore.filters}))(Search);

export {Search, InjectSearch};